/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

import { SqlQueryTab } from '@/service/modules/sqlconsole/types'
import { useSqlExecTabStore } from '@/store/sqlconsole/sql-exec-tab'
import { SqlExec } from '@/store/sqlconsole/types'
import { useDialog } from 'naive-ui'
import { inject, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { SqlConsoleSymbol } from '..'

export function useSingleSqlQuery(dbName: string) {
  const { t } = useI18n()

  const timerSet = inject(SqlConsoleSymbol, '')
  const $sqlExecTabStore = useSqlExecTabStore()
  const dialog = useDialog()

  const tabs = ref<number>(1)
  const currentSqlTab = ref<string>('')
  const sqlTabs = ref<SqlQueryTab[]>([
    {
      name: dbName + 'sql1',
      instance: dbName,
      label: 'SQL console',
      closable: false,
      bottomDivHeight: 165
    }
  ])

  const onRemoveTab = (tabName: string) => {
    // when close this sql query console tab, need to clear all setted timer
    for (let i = 0; i < sqlTabs.value.length; i++) {
      if (sqlTabs.value[i].name === tabName) {
        sqlTabs.value.splice(i, 1)
        // get all exec status
        const execStatusTabs = $sqlExecTabStore.getAllExecTabs

        // delete job and all query console tab's jobs
        $sqlExecTabStore.deleteTabByConsoleName(tabName)
        execStatusTabs.forEach((item: SqlExec) => {
          if (item.consoleName === tabName) {
            // when query console tab not existed, clear timer too.
            timerSet.clearTimer(item.jobId)
          }
        })
      }
    }
  }

  const onBeforeRemoveTab = (instance: string): Promise<boolean> => {
    return new Promise(function (resolve) {
      dialog.warning({
        title: t('explore.removeTabTip'),
        positiveText: t('common.positiveText'),
        negativeText: t('common.negativeText'),
        negativeButtonProps: {
          type: 'default'
        },
        positiveButtonProps: {
          type: 'primary'
        },
        onPositiveClick: () => {
          onRemoveTab(instance)
          resolve(true)
        }
      })
    })
  }

  const onAddSqlTab = () => {
    sqlTabs.value.push({
      name: `${dbName}sql${++tabs.value}`,
      instance: `${dbName}`,
      label: 'SQL console',
      closable: true,
      bottomDivHeight: 165
    })
    currentSqlTab.value = `${dbName}sql${tabs.value}`
  }

  // set current query console tab's height
  const onChangeConsoleBottomHeight = (height: number): any => {
    for (let i = 0; i < sqlTabs.value.length; i++) {
      if (sqlTabs.value[i].name === currentSqlTab.value) {
        sqlTabs.value[i].bottomDivHeight = height
      }
    }
  }

  onMounted(() => {
    currentSqlTab.value = sqlTabs.value[0].name
  })

  return {
    tabs,
    currentSqlTab,
    sqlTabs,
    onRemoveTab,
    onBeforeRemoveTab,
    onAddSqlTab,
    onChangeConsoleBottomHeight
  }
}
